<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>60-Atomics与SharedArrayBuffer | 小黑博客</title><meta name="keywords" content="JavaScript,JavaScript高级程序设计第四版"><meta name="author" content="BluesYoung-web"><meta name="copyright" content="BluesYoung-web"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="SharedArrayBuffer ArrayBuffer 必须在不同执行上下文之间切换 SharedArrayBuffer 可以被任意多个执行上下文同时使用 多个专用工作线程访问同一个 SharedArrayBuffer 导致的资源争用的问题  1234567891011121314151617181920212223242526272829303132const woker &#x3D; &#96;self.o">
<meta property="og:type" content="article">
<meta property="og:title" content="60-Atomics与SharedArrayBuffer">
<meta property="og:url" content="https://bluesyoung-web.gitee.io/blog/2021-01-28-60-Atomics%E4%B8%8ESharedArrayBuffer.html">
<meta property="og:site_name" content="小黑博客">
<meta property="og:description" content="SharedArrayBuffer ArrayBuffer 必须在不同执行上下文之间切换 SharedArrayBuffer 可以被任意多个执行上下文同时使用 多个专用工作线程访问同一个 SharedArrayBuffer 导致的资源争用的问题  1234567891011121314151617181920212223242526272829303132const woker &#x3D; &#96;self.o">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://bluesyoung-web.gitee.io/blog/img/hbs.png">
<meta property="article:published_time" content="2021-01-28T01:49:03.000Z">
<meta property="article:modified_time" content="2021-08-29T11:36:10.270Z">
<meta property="article:author" content="BluesYoung-web">
<meta property="article:tag" content="JavaScript">
<meta property="article:tag" content="JavaScript高级程序设计第四版">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://bluesyoung-web.gitee.io/blog/img/hbs.png"><link rel="shortcut icon" href="/blog/img/favicon.png"><link rel="canonical" href="https://bluesyoung-web.gitee.io/blog/2021-01-28-60-Atomics%E4%B8%8ESharedArrayBuffer"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="stylesheet" href="/blog/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/blog/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":50,"languages":{"author":"作者: BluesYoung-web","link":"链接: ","source":"来源: 小黑博客","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#121212","position":"top-right"},
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isanchor: true
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '60-Atomics与SharedArrayBuffer',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: false,
  postUpdate: '2021-08-29 19:36:10'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if (GLOBAL_CONFIG_SITE.isHome && /iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="/blog/css/background.css"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/sviptzk/HexoStaticFile@latest/Hexo/css/custom.min.css"></link><meta name="generator" content="Hexo 5.4.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/blog/img/lufei_siwangningshi.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data is-center"><div class="data-item"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">153</div></a></div><div class="data-item"><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">54</div></a></div><div class="data-item"><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">48</div></a></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/about/"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/blog/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/blog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/blog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/blog/img/hbs.png')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/blog/">小黑博客</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/about/"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/blog/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/blog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/blog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">60-Atomics与SharedArrayBuffer</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-01-28T01:49:03.000Z" title="发表于 2021-01-28 09:49:03">2021-01-28</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2021-08-29T11:36:10.270Z" title="更新于 2021-08-29 19:36:10">2021-08-29</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/">学习笔记</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/JavaScript%E9%AB%98%E7%BA%A7%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/">JavaScript高级程序设计</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/JavaScript%E9%AB%98%E7%BA%A7%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/%E7%AC%AC20%E7%AB%A0%E2%80%94%E2%80%94JavaScriptAPI/">第20章——JavaScriptAPI</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">1.3k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>5分钟</span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="SharedArrayBuffer"><a href="#SharedArrayBuffer" class="headerlink" title="SharedArrayBuffer"></a><code>SharedArrayBuffer</code></h2><ul>
<li><code>ArrayBuffer</code> 必须在不同执行上下文之间切换</li>
<li><code>SharedArrayBuffer</code> 可以被任意多个执行上下文<strong>同时使用</strong></li>
<li>多个专用工作线程访问同一个 <code>SharedArrayBuffer</code> 导致的<strong>资源争用</strong>的问题</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> woker = <span class="string">`</span></span><br><span class="line"><span class="string">self.onmessage = (&#123; data &#125;) =&gt; &#123;</span></span><br><span class="line"><span class="string">	const view = new Uint32Array(data);</span></span><br><span class="line"><span class="string">	for (let i = 0; i &lt; 1E6; i++) &#123;</span></span><br><span class="line"><span class="string">		view[0] += 1;</span></span><br><span class="line"><span class="string">	&#125;</span></span><br><span class="line"><span class="string">	self.postMessage(null);</span></span><br><span class="line"><span class="string">&#125;</span></span><br><span class="line"><span class="string">`</span>;</span><br><span class="line"><span class="keyword">const</span> wokerScriptBlobUrl = <span class="built_in">window</span>.URL.createObjectURL(<span class="keyword">new</span> Blob([woker]));</span><br><span class="line"><span class="comment">// 创建容量为 4 的工作线程池</span></span><br><span class="line"><span class="keyword">const</span> workers = [];</span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; <span class="number">4</span>; i++) &#123;</span><br><span class="line">  workers.push(<span class="keyword">new</span> Worker(wokerScriptBlobUrl));</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 在最后一个工作线程完成后打印出最终值</span></span><br><span class="line"><span class="keyword">let</span> resCount = <span class="number">0</span>;</span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">const</span> worker <span class="keyword">of</span> workers) &#123;</span><br><span class="line">  worker.onmessage = <span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (++resCount === workers.length) &#123;</span><br><span class="line">      <span class="built_in">console</span>.log(<span class="string">`Final buffer value: <span class="subst">$&#123;view[<span class="number">0</span>]&#125;</span>`</span>);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 初始化 SharedArrayBuffer</span></span><br><span class="line"><span class="keyword">const</span> sharedArrayBuffer = <span class="keyword">new</span> SharedArrayBuffer(<span class="number">4</span>);</span><br><span class="line"><span class="keyword">const</span> view = <span class="keyword">new</span> <span class="built_in">Uint32Array</span>(sharedArrayBuffer);</span><br><span class="line">view[<span class="number">0</span>] = <span class="number">1</span>; </span><br><span class="line"><span class="comment">// 把 SharedArrayBuffer 发送到每个工作线程</span></span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">const</span> worker <span class="keyword">of</span> workers) &#123;</span><br><span class="line">  worker.postMessage(sharedArrayBuffer);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="原子操作"><a href="#原子操作" class="headerlink" title="原子操作"></a>原子操作</h2><ul>
<li>任何全局上下文中都有 <code>Atomics</code> 对象</li>
<li>这个对象上暴露了用于执行线程安全操作的一套静态方法</li>
<li>其中多数方法以一个 <code>SharedArrayBuffer</code> 的引用作为第一个参数</li>
<li>以相关操作数作为后续参数</li>
</ul>
<h3 id="算术及位操作方法"><a href="#算术及位操作方法" class="headerlink" title="算术及位操作方法"></a>算术及位操作方法</h3><ul>
<li>从某个位置读取值</li>
<li>然后从某个位置读取值，并执行相关操作</li>
<li>最后把计算结果写回相同的位置</li>
<li><code>Atomics.add(typeArray, index, value)</code> 原子加</li>
<li><code>Atomics.sub(typeArray, index, value)</code> 原子减</li>
<li><code>Atomics.or(typeArray, index, value)</code> 原子或</li>
<li><code>Atomics.and(typeArray, index, value)</code> 原子与</li>
<li><code>Atomics.xor(typeArray, index, value)</code> 原子异或</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 线程安全的加操作</span></span><br><span class="line"><span class="keyword">const</span> woker = <span class="string">`</span></span><br><span class="line"><span class="string">self.onmessage = (&#123; data &#125;) =&gt; &#123;</span></span><br><span class="line"><span class="string">	const view = new Uint32Array(data);</span></span><br><span class="line"><span class="string">	for (let i = 0; i &lt; 1E6; i++) &#123;</span></span><br><span class="line"><span class="string">		// 线程安全的加操作</span></span><br><span class="line"><span class="string"> 		Atomics.add(view, 0, 1);</span></span><br><span class="line"><span class="string">	&#125;</span></span><br><span class="line"><span class="string">	self.postMessage(null);</span></span><br><span class="line"><span class="string">&#125;</span></span><br><span class="line"><span class="string">`</span>;</span><br></pre></td></tr></table></figure>

<h3 id="原子读和写"><a href="#原子读和写" class="headerlink" title="原子读和写"></a>原子读和写</h3><ul>
<li>浏览器的 <code>JavaScript</code> 编译器和 <code>CPU</code> 架构本身都有权限重排指令以提升程序执行效率</li>
<li>正常情况下， <code>JavaScript</code> 的单线程环境是可以随时进行这种优化的</li>
<li>但多线程下的指令重排可能导致资源争用，而且极难排错</li>
<li><strong>所有原子指令相互之间的顺序永远不会重排</strong></li>
<li>使用原子读或原子写保证所有指令（包括原子和非原子指令）都不会相对原子读/写重新排序</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> sharedArrayBuffer = <span class="keyword">new</span> SharedArrayBuffer(<span class="number">4</span>);</span><br><span class="line"><span class="keyword">const</span> view = <span class="keyword">new</span> <span class="built_in">Uint32Array</span>(sharedArrayBuffer);</span><br><span class="line"><span class="comment">// 执行非原子写</span></span><br><span class="line">view[<span class="number">0</span>] = <span class="number">1</span>;</span><br><span class="line"><span class="comment">// 非原子写可以保证在这个读操作之前完成，因此这里一定会读到 1</span></span><br><span class="line"><span class="built_in">console</span>.log(Atomics.load(view, <span class="number">0</span>)); <span class="comment">// 1</span></span><br><span class="line"><span class="comment">// 执行原子写</span></span><br><span class="line">Atomics.store(view, <span class="number">0</span>, <span class="number">2</span>);</span><br><span class="line"><span class="comment">// 非原子读可以保证在原子写完成后发生，因此这里一定会读到 2</span></span><br><span class="line"><span class="built_in">console</span>.log(view[<span class="number">0</span>]); <span class="comment">// 2 </span></span><br></pre></td></tr></table></figure>

<h3 id="原子交换"><a href="#原子交换" class="headerlink" title="原子交换"></a>原子交换</h3><ul>
<li><code>Atomics.exchange()</code> 执行简单的交换，以保证其他线程不会中断值的交换</li>
<li><code>Atomics.compareExchange()</code> 只在目标索引处的值与预期值匹配时才会执行写操作</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> sharedArrayBuffer = <span class="keyword">new</span> SharedArrayBuffer(<span class="number">4</span>);</span><br><span class="line"><span class="keyword">const</span> view = <span class="keyword">new</span> <span class="built_in">Uint32Array</span>(sharedArrayBuffer);</span><br><span class="line"><span class="comment">// 在索引 0 处写入 3</span></span><br><span class="line">Atomics.store(view, <span class="number">0</span>, <span class="number">3</span>);</span><br><span class="line"><span class="comment">// 从索引 0 处读取值，然后在索引 0 处写入 4</span></span><br><span class="line"><span class="built_in">console</span>.log(Atomics.exchange(view, <span class="number">0</span>, <span class="number">4</span>)); <span class="comment">// 3</span></span><br><span class="line"><span class="comment">// 从索引 0 处读取值</span></span><br><span class="line"><span class="built_in">console</span>.log(Atomics.load(view, <span class="number">0</span>)); <span class="comment">// 4</span></span><br><span class="line"><span class="comment">// -------------------------------</span></span><br><span class="line"><span class="keyword">const</span> sharedArrayBuffer = <span class="keyword">new</span> SharedArrayBuffer(<span class="number">4</span>);</span><br><span class="line"><span class="keyword">const</span> view = <span class="keyword">new</span> <span class="built_in">Uint32Array</span>(sharedArrayBuffer);</span><br><span class="line"><span class="comment">// 在索引 0 处写入 5</span></span><br><span class="line">Atomics.store(view, <span class="number">0</span>, <span class="number">5</span>);</span><br><span class="line"><span class="comment">// 从缓冲区读取值</span></span><br><span class="line"><span class="keyword">let</span> initial = Atomics.load(view, <span class="number">0</span>);</span><br><span class="line"><span class="comment">// 对这个值执行非原子操作</span></span><br><span class="line"><span class="keyword">let</span> result = initial ** <span class="number">2</span>;</span><br><span class="line"><span class="comment">// 只在缓冲区未被修改的情况下才会向缓冲区写入新值</span></span><br><span class="line">Atomics.compareExchange(view, <span class="number">0</span>, initial, result);</span><br><span class="line"><span class="comment">// 检查写入成功</span></span><br><span class="line"><span class="built_in">console</span>.log(Atomics.load(view, <span class="number">0</span>)); <span class="comment">// 25</span></span><br><span class="line"><span class="comment">// 只在缓冲区未被修改的情况下才会向缓冲区写入新值</span></span><br><span class="line">Atomics.compareExchange(view, <span class="number">0</span>, -<span class="number">1</span>, result);</span><br><span class="line"><span class="comment">// 检查写入失败</span></span><br><span class="line"><span class="built_in">console</span>.log(Atomics.load(view, <span class="number">0</span>)); <span class="comment">// 5 </span></span><br></pre></td></tr></table></figure>

<h3 id="原子-Futex-操作与加锁"><a href="#原子-Futex-操作与加锁" class="headerlink" title="原子 Futex 操作与加锁"></a>原子 <code>Futex</code> 操作与加锁</h3><ul>
<li><code>Futex</code>(<code>fast user-space mutex</code>) 快速用户空间互斥量</li>
<li><code>Atomics.wait()</code> 每个工作线程到达之后就会停止执行</li>
<li>在停止状态下，执行线程存在于一个<strong>等待队列</strong>中</li>
<li>在经过指定时间或在相应索引上调用 <code>Atomics.notify()</code> 释放其中一个等待的线程</li>
<li>这个线程执行完毕后会再次调用 <code>Atomics.notify()</code> 释放另一个线程</li>
<li><code>Atomics.isLockFree()</code> 在高性能算法中可以用来确定是都有必要获取锁</li>
</ul>
<blockquote>
<p>所有原子 <code>Futex</code> 操作只能用于 <code>Int32Array</code> 视图。而且，也只能用在工作线程内部</p>
</blockquote>
<h2 id="XDM"><a href="#XDM" class="headerlink" title="XDM"></a><code>XDM</code></h2><ul>
<li><code>cross-document messaging</code> 跨文档消息</li>
<li><code>targetWindow.postMessage(msg, targetSource, [transfer])</code>：<ul>
<li><code>targetWindow</code> 对将要接收消息的窗口的引用</li>
<li><code>msg</code> 要发送的数据</li>
<li><code>transfer</code> 与消息一起传输的 <code>Transferable</code> 对象序列</li>
</ul>
</li>
<li><code>event</code>：<ul>
<li><code>data</code> 收到的消息</li>
<li><code>origin</code> 发送消息的文档源</li>
<li><code>source</code> 发送消息的文档中 <code>window</code> 对象的代理</li>
</ul>
</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 发送端</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">var</span> iframeWindow = <span class="built_in">document</span>.querySelector(<span class="string">&#x27;iframe&#x27;</span>).contentWindow;</span><br><span class="line"><span class="comment">/////////////////////////////////////////</span></span><br><span class="line"><span class="keyword">var</span> opener = <span class="built_in">window</span>.open(<span class="string">&#x27;http://117.78.0.214/testResult&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> sendTarget = opener || iframeWindow;</span><br><span class="line"><span class="keyword">var</span> msg = &#123;</span><br><span class="line">    status: <span class="number">0</span>,</span><br><span class="line">    data: <span class="string">&#x27;hello world&#x27;</span>,</span><br><span class="line">    msg: <span class="string">&#x27;&#x27;</span></span><br><span class="line">&#125;</span><br><span class="line">sendTarget.postMessage(<span class="built_in">JSON</span>.stringify(msg), <span class="string">&#x27;https://feeds.qq.com&#x27;</span>);</span><br><span class="line"><span class="built_in">window</span>.onmessage = <span class="function"><span class="keyword">function</span>(<span class="params">event</span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="built_in">JSON</span>.parse(event.data));</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 接收端</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="built_in">window</span>.onmessage = <span class="function"><span class="keyword">function</span>(<span class="params">event</span>)</span>&#123;</span><br><span class="line">    <span class="comment">// 防止跨站点脚本攻击</span></span><br><span class="line">    <span class="keyword">if</span>(event.origin == <span class="string">&#x27;https://feeds.qq.com&#x27;</span>)&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="built_in">JSON</span>.parse(event.data));</span><br><span class="line">        <span class="comment">// 回复</span></span><br><span class="line">        <span class="keyword">var</span> msg = &#123;</span><br><span class="line">            status: <span class="number">0</span>,</span><br><span class="line">            data: <span class="string">&#x27;hello&#x27;</span>,</span><br><span class="line">            msg: <span class="string">&#x27;&#x27;</span></span><br><span class="line">        &#125;</span><br><span class="line">        event.source.postMessage(<span class="built_in">JSON</span>.stringify(msg), <span class="string">&#x27;http://117.78.0.214&#x27;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">BluesYoung-web</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://bluesyoung-web.gitee.io/blog/2021-01-28-60-Atomics%E4%B8%8ESharedArrayBuffer.html">https://bluesyoung-web.gitee.io/blog/2021-01-28-60-Atomics%E4%B8%8ESharedArrayBuffer.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://BluesYoung-web.gitee.io/blog" target="_blank">小黑博客</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/blog/tags/JavaScript/">JavaScript</a><a class="post-meta__tags" href="/blog/tags/JavaScript%E9%AB%98%E7%BA%A7%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1%E7%AC%AC%E5%9B%9B%E7%89%88/">JavaScript高级程序设计第四版</a></div><div class="post_share"></div></div><div class="post-reward"><div class="reward-button button--animated"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="/blog/img/wx.png" target="_blank"><img class="post-qr-code-img" src="/blog/img/wx.png" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="/blog/img/zfb.jpg" target="_blank"><img class="post-qr-code-img" src="/blog/img/zfb.jpg" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/blog/2020-12-28-01-历史回顾.html" title="01-历史回顾"><img class="cover" src="/blog/img/hbs.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-12-28</div><div class="title">01-历史回顾</div></div></a></div><div><a href="/blog/2020-12-28-03-script元素.html" title="03-script元素"><img class="cover" src="/blog/img/hbs.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-12-28</div><div class="title">03-script元素</div></div></a></div><div><a href="/blog/2020-12-28-02-实现.html" title="02-实现"><img class="cover" src="/blog/img/hbs.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-12-28</div><div class="title">02-实现</div></div></a></div><div><a href="/blog/2020-12-28-04-文档模式.html" title="04-文档模式"><img class="cover" src="/blog/img/hbs.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-12-28</div><div class="title">04-文档模式</div></div></a></div><div><a href="/blog/2020-12-28-05-语法.html" title="05-语法"><img class="cover" src="/blog/img/hbs.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-12-28</div><div class="title">05-语法</div></div></a></div><div><a href="/blog/2020-12-28-06-变量声明.html" title="06-变量声明"><img class="cover" src="/blog/img/hbs.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-12-28</div><div class="title">06-变量声明</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/blog/img/lufei_siwangningshi.jpg" onerror="this.onerror=null;this.src='/blog/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">BluesYoung-web</div><div class="author-info__description">一枚不善言辞的技术宅</div></div><div class="card-info-data is-center"><div class="card-info-data-item"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">153</div></a></div><div class="card-info-data-item"><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">54</div></a></div><div class="card-info-data-item"><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">48</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://gitee.com/BluesYoung-web"><i class="fab fa-gitee"></i><span>点个小星星吧</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/BluesYoung-web" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="mailto:15171255945@163.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a></div></div><div class="sticky_layout"><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/blog/2021-08-24-%E7%A7%BB%E5%8A%A8%E7%AB%AF%E8%BD%AF%E9%94%AE%E7%9B%98%E5%AF%BC%E8%87%B4%E5%B8%83%E5%B1%80%E9%94%99%E4%B9%B1.html" title="移动端软键盘导致布局错乱"><img src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="移动端软键盘导致布局错乱"/></a><div class="content"><a class="title" href="/blog/2021-08-24-%E7%A7%BB%E5%8A%A8%E7%AB%AF%E8%BD%AF%E9%94%AE%E7%9B%98%E5%AF%BC%E8%87%B4%E5%B8%83%E5%B1%80%E9%94%99%E4%B9%B1.html" title="移动端软键盘导致布局错乱">移动端软键盘导致布局错乱</a><time datetime="2021-08-24T10:01:20.000Z" title="发表于 2021-08-24 18:01:20">2021-08-24</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2021-08-16-Linux%E5%AE%89%E8%A3%85you-get.html" title="Linux安装you-get"><img src="/blog/img/shumeipai_cover.jpg" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="Linux安装you-get"/></a><div class="content"><a class="title" href="/blog/2021-08-16-Linux%E5%AE%89%E8%A3%85you-get.html" title="Linux安装you-get">Linux安装you-get</a><time datetime="2021-08-16T08:07:31.000Z" title="发表于 2021-08-16 16:07:31">2021-08-16</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2021-08-16-git%E5%88%A0%E9%99%A4%E8%BF%9C%E7%A8%8B%E4%BB%93%E5%BA%93%E7%9A%84%E6%8F%90%E4%BA%A4.html" title="git删除远程仓库的提交"><img src="/blog/img/skill.jpg" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="git删除远程仓库的提交"/></a><div class="content"><a class="title" href="/blog/2021-08-16-git%E5%88%A0%E9%99%A4%E8%BF%9C%E7%A8%8B%E4%BB%93%E5%BA%93%E7%9A%84%E6%8F%90%E4%BA%A4.html" title="git删除远程仓库的提交">git删除远程仓库的提交</a><time datetime="2021-08-16T07:52:02.000Z" title="发表于 2021-08-16 15:52:02">2021-08-16</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2021-08-13-%E5%B0%86pad%E6%89%A9%E5%B1%95%E4%B8%BA%E7%94%B5%E8%84%91%E7%9A%84%E5%89%AF%E5%B1%8F.html" title="将pad扩展为电脑的副屏"><img src="/blog/img/skill.jpg" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="将pad扩展为电脑的副屏"/></a><div class="content"><a class="title" href="/blog/2021-08-13-%E5%B0%86pad%E6%89%A9%E5%B1%95%E4%B8%BA%E7%94%B5%E8%84%91%E7%9A%84%E5%89%AF%E5%B1%8F.html" title="将pad扩展为电脑的副屏">将pad扩展为电脑的副屏</a><time datetime="2021-08-13T11:44:04.000Z" title="发表于 2021-08-13 19:44:04">2021-08-13</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2021-08-11-Linux%E5%90%AF%E7%94%A8SSH%E6%9C%8D%E5%8A%A1.html" title="Linux启用SSH服务"><img src="/blog/img/shumeipai_cover.jpg" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="Linux启用SSH服务"/></a><div class="content"><a class="title" href="/blog/2021-08-11-Linux%E5%90%AF%E7%94%A8SSH%E6%9C%8D%E5%8A%A1.html" title="Linux启用SSH服务">Linux启用SSH服务</a><time datetime="2021-08-11T10:50:04.000Z" title="发表于 2021-08-11 18:50:04">2021-08-11</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2021 By BluesYoung-web</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/blog/js/utils.js"></script><script src="/blog/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script src="/blog/js/search/local-search.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"><script>if (document.getElementsByClassName('mermaid').length) {
  if (window.mermaidJsLoad) mermaid.init()
  else {
    getScript('https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js').then(() => {
      window.mermaidJsLoad = true
      mermaid.initialize({
        theme: 'default',
      })
      false && mermaid.init()
    })
  }
}</script></div><script src="https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js"></script> <script src="/blog/js/xkTool.js"></script> <script src="/blog/js/mySelf.js"></script><canvas class="fireworks" mobile="false"></canvas><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/fireworks.min.js"></script><script id="canvas_nest" defer="defer" color="0,0,255" opacity="0.7" zIndex="-1" count="99" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-nest.min.js"></script></div></body></html>